<?php

//作为接口传输的时候认证的密钥
$valid_token = 'd49dfa762268687eb2ca59498ce852';
//调用接口被允许的ip地址
$valid_ip = array('118.190.56.30', '182.150.28.165', '39.98.154.137');
$client_token = $_SERVER['HTTP_X_GITLAB_TOKEN'];
$client_ip = $_SERVER['REMOTE_ADDR'];
$fs = fopen('./auto_hook.log', 'a+');
fwrite($fs, 'Request on [' . date('Y-m-d h:i:s', time()) . '] from [' . $client_ip . ']' . PHP_EOL);
if ($client_token !== $valid_token) {
    echo "error 10001";
    fwrite($fs, "Invalid token [{$client_token}]" . PHP_EOL);
    exit(0);
}
if (!in_array($client_ip, $valid_ip)) {
    echo "error 10002";
    fwrite($fs, "Invalid ip [{$client_ip}]" . PHP_EOL);
    exit(0);
}
$json = file_get_contents('php://input');
$data = json_decode($json, true);
foreach ($data['commits'] as $commit){
    fwrite($fs, 'Message: ' . $commit['message'] . PHP_EOL);
    fwrite($fs, 'Author: ' . $commit['author']['name'] . PHP_EOL);
    fwrite($fs, 'Modified: ' . json_encode($commit['modified']) . PHP_EOL);
}
//exec('sudo bash /alidata/sh/git_pull.sh', $output);
//print_r(json_encode($output).PHP_EOL);
shell_exec("cd /alidata/www/youmi_api_v2");
shell_exec("sudo /usr/bin/git pull >> syncLog.txt 2>&1");
shell_exec("sudo php /alidata/www/youmi_api_v2/bin/laravels stop >> syncLog.txt 2>&1");
shell_exec("sudo nohup php /alidata/www/youmi_api_v2/bin/laravels start >> syncLog.txt 2>&1 &");
shell_exec("sudo echo -e '\n' ");
fwrite($fs, '=======================================================================' . PHP_EOL);
fclose($fs);
